package iconcurrent;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * @author or2
 * @Description 探究 JVM线程的状态
 * @create 2021年09月10日 时间: 16:57
 */
public class StatusOfThread {
    public static void main(String[] args) throws InterruptedException {
        Runnable task = () -> {
            synchronized (StatusOfThread.class) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread thread = new Thread(task, "Noraml");

//        线程状态 ① - NEW
        System.out.println(thread.getState());

//        线程状态 ② - Runnable (可运行, 运行中)
        thread.start();
        System.out.println(thread.getState());

//        线程状态 ③ - Blocked
        Thread threadBlocked = new Thread(task, "Blocked");
        threadBlocked.start();
        // 给点时间, 让线程抢锁
        Thread.sleep(1);
        System.out.println(threadBlocked.getState());

//        线程状态 ④ - Waiting
        Thread threadWait = new Thread(LockSupport::park, "Wating");
        threadWait.start();
        Thread.sleep(1);
        System.out.println(threadWait.getState());
        LockSupport.unpark(threadWait);

//        线程状态 ⑤ - Timed_Waiting
        System.out.println(thread.getState());

//        线程状态 ⑥ - Terminated
        Thread threadTerminated = new Thread(() -> {
        });
        threadTerminated.start();
        Thread.sleep(1);
        System.out.println(threadTerminated.getState());
    }
}
